var bc_process_vars = {
		"po_sent_status" : null,
		"inv_recd_status" : null,
		"cm_recd_status" : null,
		"pmt_sent_status" : null
};


var bc_pvar_int = null;

jQuery(document).ready(function() {
	init_posent();
	init_invreceived();
	init_cmemoreceived();
	init_pmtsent();
	var d = new Date();
	var s2 = format_date(d);
	d.setDate(d.getDate() - 7)
	var s1 = format_date(d);
	dwr.util.setValue('bc_last_seven', s1 + ' - ' + s2);
	
	init_buyer_main(); 	
	clearInterval(bc_pvar_int);
	bc_pvar_int = null;
	bc_pvar_int = setInterval(bc_check_initprocesses,2000);
	
});

function init_buyer_main(){
	bc_process_vars.cm_recd_status = null;
	bc_process_vars.inv_recd_status = null;
	bc_process_vars.pmt_sent_status = null;
	bc_process_vars.po_sent_status = null;
	
	//Show PO Sent as default for buyer context
	jQuery('#bc_po_sent_a').removeClass('showlist');
	jQuery('#bc_po_sent_a').addClass('hide');
	jQuery('#bc_po_sent_sp').removeClass('hide');
	jQuery('#bc_po_sent_sp').addClass('showlist visitedbold');
	jQuery('#ctx_bc_po_sent_tbldiv').removeClass('hide');
	jQuery('#ctx_bc_po_sent_tbldiv').addClass('show');
	jQuery('#bc_activity_throbber').removeClass('throbberOff').addClass('throbberOn');
	dwr.util.removeAllRows("bc_notifications_body", {filter:function (tr) {return (tr.id != "bc_notifications_pattern");}});
	posent_cache = [];
	render_jqpostable();
	
	//Reset notification header.
	dwr.util.setValue('bc_notifications_header','Loading messages...');
	jQuery('#bc_notifications_throbber').removeClass('notif_throbberOff').addClass('notif_throbberOn');
	//Get notifications.
	c_get_notifications(true);
	
}

function bc_check_initprocesses(){
	if(!isEmptyString(bc_process_vars.cm_recd_status)
			&& !isEmptyString(bc_process_vars.inv_recd_status)
			&& !isEmptyString(bc_process_vars.pmt_sent_status)
			&& !isEmptyString(bc_process_vars.po_sent_status)){
		jQuery('#bc_activity_throbber').removeClass('throbberOn').addClass('throbberOff');
		clearInterval(bc_pvar_int);
		bc_pvar_int = null;
	}
	
	//Check for errors on individual statuses
}



// u10102@email.com
// var usrcompany_uid = 'C1318576975393';
// var usrcomp_comapnyId = 'sj _1318576975393';

function init_posent() {
	var dwrCallMetaData = {
		callback : success_findpobysupp,
		exceptionHandler : ysn_dwrerror_handler,
		timeout : 100000,
		errorHandler : ysn_dwrerror_handler
	};

	DWR_PurchaseOrders.fetchPurchaseOrdersForCompany(usrcompany_uid, true,
			false, dwrCallMetaData);
}

var posent_cache = null;

function success_findpobysupp(dwrresp) {

	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null
				&& dwrresp.objRespOrError["PO_SENT"] != null
				&& dwrresp.objRespOrError["PO_SENT"].length > 0) {
			posent_cache = dwrresp.objRespOrError["PO_SENT"];
			bc_process_vars.po_sent_status = "0";
		}
	}else{
		posent_cache  = [];
		bc_process_vars.po_sent_status = "1";
	}
	
	render_jqpostable();
}

var ctx_posent_table = null;
function render_jqpostable() {
	if(ctx_posent_table != null){
		ctx_posent_table.fnDestroy();
		ctx_posent_table = null;
	}
	ctx_posent_table = jQuery('#ctx_bc_po_sent_tbl').dataTable({
		"bProcessing" : true,
		"aaData" : posent_cache,
		"bJQueryUI" : true,
		"bSortClasses" : false,
		"aoColumns" : [ {
			"mDataProp" : "orderNumber",
			"sClass": "alignCenter",
			"fnRender" : function(obj) {
				var onum = obj.aData.orderNumber;

				return "<a href='javascript:void(0);'>" + onum + "</a>";
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : "orderDate",
			"sType" : "date",
			"sClass": "alignCenter",
			"fnRender" : function(obj) {

				return format_date(obj.aData.orderDate);
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : "clientNameText",
			"sClass": "alignCenter"
			
		}, {
			"mDataProp" : "orderAmount",
			"sClass": "alignCenter",
			"fnRender" : function(obj) {
				var om = (isEmptyString(obj.aData.unitCurrencySymbol)? "USD" : obj.aData.unitCurrencySymbol )+ " " +  format_currency(obj.aData.orderAmount);
				
				return om;
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : "invoicedAmount",
			"sClass": "alignCenter",
			"fnRender" : function(obj) {
				var om = (isEmptyString(obj.aData.unitCurrencySymbol)? "USD" : obj.aData.unitCurrencySymbol )+ " " +  format_currency(obj.aData.invoicedAmount);
				
				return om;
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : "poStatus",
			"sClass": "alignCenter",
			"fnRender" : function(obj) {
				return getStatus(obj.aData.poStatus);
			},
			"bUseRendered" : false
		},{
			"mDataProp" : "orderOwner","sClass": "alignCenter"
		},{
			"mDataProp" : "versionNumber","sClass": "alignCenter"
		} ]
	});
	
	
	//ctx_posent_table.children('td').attr('align', 'center');

}

function getStatus(status){
	var om = status;
	
	if(isEmptyString(om) || om == G_STATUS_MAP["PO_STATUS_NEW"]){
		om = "Sent"
	}else if(om == G_STATUS_MAP["PO_STATUS_NEW"]){
		om = "Fully Invoiced";
	}else if(om == G_STATUS_MAP["PO_STATUS_FULLY_INVOICED"]){
		om = "Fully Invoiced";
	}else if(om == G_STATUS_MAP["PO_STATUS_PARTIALLY_INVOICED"]){
		om = "Partially Invoiced";
	}else if(om == G_STATUS_MAP["PO_STATUS_CANCELLED"]){
		om = "Cancelled";
	}else if(om == G_STATUS_MAP["PO_STATUS_FAILED"]){
		om = "Failed";
	}else {
		om = "Status not Available."
	}
	return om;
}

function init_invreceived() {

	var dwrCallMetaData = {
		callback : success_fetchinvoicerecd,
		exceptionHandler : ysn_dwrerror_handler,
		timeout : 100000,
		errorHandler : ysn_dwrerror_handler
	};

	DWR_Invoice.fetchInvoicesReceived(usrcompany_uid, dwrCallMetaData);
}

var ctx_invrecd_table = null;
function render_jqinvrtable() {
	ctx_invrecd_table = jQuery('#ctx_bc_inv_recd_tbl').dataTable({
		"bProcessing" : true,
		"aaData" : inv_recdcache,
		"bJQueryUI" : true,
		"bSortClasses" : false,
		"aoColumns" : [ {
			"mDataProp" : "invoiceNumber","sClass": "alignCenter",
			"fnRender" : function(obj) {
				var onum = obj.aData.invoiceNumber;

				return "<a href='javascript:void(0);'>" + onum + "</a>";
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : "supplierNameText","sClass": "alignCenter",
			"sClass": "alignRight" 
		}, {
			"mDataProp" : "totalInvoiceAmount",
			"fnRender" : function(obj) {
				var om = (isEmptyString(obj.aData.unitCurrencySymbol)? "USD" : obj.aData.unitCurrencySymbol )+ " " +  format_currency(obj.aData.totalInvoiceAmount);
				
				return om;
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : "invoiceDate","sClass": "alignCenter",
			"sType" : "date",
			"fnRender" : function(obj) {

				return format_date(obj.aData.invoiceDate);
			},
			"bUseRendered" : false
		},

		{
			"mDataProp" : "purchaseOrderNumber","sClass": "alignCenter",
			"fnRender" : function(obj) {
				var onum = obj.aData.purchaseOrderNumber;

				return "<a href='javascript:void(0);'>" + onum + "</a>";
			},
			"bUseRendered" : false
		},  {
			"mDataProp" : "invStatus","sClass": "alignCenter",
			"fnRender" : function(obj) {
				var om = obj.aData.invStatus;
				
				if(isEmptyString(om) || om == G_STATUS_MAP["INV_STATUS_NEW"]){
					om = "Received"
				}else if(om == G_STATUS_MAP["INV_STATUS_ACCEPTED"]){
					om = "Accepted";
				}else if(om == G_STATUS_MAP["INV_STATUS_REJECTED"]){
					om = "Rejected";
				}else if(om == G_STATUS_MAP["INV_STATUS_FAILED"]){
					om = "Failed";
				}else if(om == G_STATUS_MAP["INV_STATUS_FULLY_PAID"]){
					om = "Fully Paid";
				}else if(om == G_STATUS_MAP["INV_STATUS_PARTIALLY_PAID"]){
					om = "Partially Paid";
				}else {
					om = "Status not Available."
				}
				
				return om;
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : "invoiceVersion","sClass": "alignCenter",
			"fnRender" : function(obj) {
				return "Show Payment Info in this column";
			},
			"bUseRendered" : false
		} ]
	});
}

var inv_recdcache = null;

function success_fetchinvoicerecd(dwrresp) {
	inv_recdcache = null;
	if (dwrresp.objRespOrError != null && dwrresp.objRespOrError.length > 0) {
		inv_recdcache = dwrresp.objRespOrError;
		bc_process_vars.inv_recd_status = "0";
	}else{
		inv_recdcache =[];
		bc_process_vars.inv_recd_status = "1";
	}
	
	render_jqinvrtable();
}

function init_cmemoreceived() {
	var dwrCallMetaData = {
		callback : success_fetchcmemorecd,
		exceptionHandler : ysn_dwrerror_handler,
		timeout : 100000,
		errorHandler : ysn_dwrerror_handler
	};

	DWR_Invoice.fetchCreditMemoReceived(usrcompany_uid, dwrCallMetaData);
}

var cmemo_recd_cache = null;
function success_fetchcmemorecd(dwrresp) {

	if (dwrresp.objRespOrError != null && dwrresp.objRespOrError.length > 0) {
		cmemo_recd_cache = dwrresp.objRespOrError;
		bc_process_vars.cm_recd_status = "0";
	}else {
		cmemo_recd_cache = [];
		bc_process_vars.cm_recd_status = "1";
	}
	render_jqcmemorecdtable();
}

var ctx_cmemorecd_table = null;
function render_jqcmemorecdtable() {
	ctx_cmemorecd_table = jQuery('#ctx_bc_cm_recd_tbl').dataTable({
		"bProcessing" : true,
		"aaData" : cmemo_recd_cache,
		"bJQueryUI" : true,
		"bSortClasses" : false,
		"aoColumns" : [ {
			"mDataProp" : "creditMemoNumber","sClass": "alignCenter",
			"fnRender" : function(obj) {
				var onum = obj.aData.creditMemoNumber;

				return "<a href='javascript:void(0);'>" + onum + "</a>";
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : "creditMemoFromCompanyName","sClass": "alignCenter",
		},

		 {
			"mDataProp" : "totalCreditMemoAmount","sClass": "alignCenter",
			"fnRender" : function(obj) {
				var om = (isEmptyString(obj.aData.unitCurrencySymbol)? "USD" : obj.aData.unitCurrencySymbol )+ " " +  format_currency(obj.aData.totalCreditMemoAmount);
				
				return om;
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : "creditMemoDate","sClass": "alignCenter",
			"sType" : "date",
			"fnRender" : function(obj) {

				return format_date(obj.aData.creditMemoDate);
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : "invoiceNumber","sClass": "alignCenter",
			"sType" : "date",
			"fnRender" : function(obj) {

				var onum = obj.aData.invoiceNumber;

				return "<a href='javascript:void(0);'>" + onum + "</a>";
			},
			"bUseRendered" : false
		},  {
			"mDataProp" : "cmStatus","sClass": "alignCenter",
			"fnRender" : function(obj) {
				var om = obj.aData.cmStatus;
				
				if(isEmptyString(om) || om == G_STATUS_MAP["CMO_STATUS_NEW"]){
					om = "Received"
				}else if(om == G_STATUS_MAP["CMO_STATUS_ACCEPTED"]){
					om = "Accepted";
				}else if(om == G_STATUS_MAP["CMO_STATUS_REJECTED"]){
					om = "Rejected";
				}else if(om == G_STATUS_MAP["CMO_STATUS_FAILED"]){
					om = "Failed";
				}else {
					om = "Status not Available."
				}
				
				return om;
			},
			"bUseRendered" : false
		}]
	});
}

function init_pmtsent() {
	pmt_sent_cache = null;
	var dwrCallMetaData = {
		callback : success_fetchpmtsent,
		exceptionHandler : ysn_dwrerror_handler,
		timeout : 100000,
		errorHandler : ysn_dwrerror_handler
	};
	DWR_Invoice.fetchPaymentsSent(usrcomp_comapnyId, dwrCallMetaData);

}
var pmt_sent_cache = null;
function success_fetchpmtsent(dwrresp) {

	if (dwrresp.objRespOrError != null && dwrresp.objRespOrError.length > 0) {
		pmt_sent_cache = dwrresp.objRespOrError;
		bc_process_vars.pmt_sent_status = "0";
	}else{
		pmt_sent_cache = [];
		bc_process_vars.pmt_sent_status = "1";
	}
	render_jqpmtsenttable();
}

var ctx_pmtsent_table = null;
function render_jqpmtsenttable() {
	ctx_pmtsent_table = jQuery('#ctx_bc_pmt_sent_tbl').dataTable({
		"bProcessing" : true,
		"aaData" : pmt_sent_cache,
		"bJQueryUI" : true,
		"bSortClasses" : false,
		"aoColumns" : [ {
			"mDataProp" : "paymentNumber","sClass": "alignCenter",
			"fnRender" : function(obj) {
				var onum = obj.aData.paymentNumber;

				return "<a href='javascript:void(0);'>" + onum + "</a>";
			},
			"bUseRendered" : false
		},
		 {
			"mDataProp" : "paymentToCompanyName","sClass": "alignCenter"
		},  {
			"mDataProp" : "totalPaymentAmount","sClass": "alignCenter",
			"fnRender" : function(obj) {
				var om = (isEmptyString(obj.aData.unitCurrencySymbol)? "USD" : obj.aData.unitCurrencySymbol )+ " " +  format_currency(obj.aData.totalPaymentAmount);
				
				return om;
			},
			"bUseRendered" : false
		},{
			"mDataProp" : "paymentType","sClass": "alignCenter",
		},{
			"mDataProp" : "paymentVersion","sClass": "alignCenter",
			"fnRender" : function(obj) {
				return "Show Payment Sent To in this column";
			},
			"bUseRendered" : false
		} 

		 ]
	});
}

function showNewPOScreen(){
	hideAllScreen();
	jQuery('#poContainer').addClass('show').removeClass('hide'); //first screen of user profile
	po_initpocreatescreen();
}

function showSentPO(){
	hideAllScreen();
	jQuery('#poListContainer').addClass('show').removeClass('hide'); //first screen of user profile
	render_jqpos_all_table();
	
}



function showNewPaymentScreen(){
	hideAllScreen();
	jQuery('#newPaymentContainer').addClass('show').removeClass('hide');
	initPaymentCreateScreen();
}

var liCounter = 0; //This variable will only reset for new PO. It will always increase.We are not changing field Id with line item number.
var ctx_buyer_LItable = null;
function testme(nFoot,aaData, iStart, iEnd,aiDisplay ){
	for ( var i=0 ; i<aaData.length ; i++ )
	{
		aaData[i][1] = i+1 ;
	}
    
}

function render_jqLineItemTable() {
	ctx_buyer_LItable = jQuery('#ctx_buyer_line_item_tbl').dataTable({
		"aaData" : {},
		"bJQueryUI" : true,
		"bSortClasses" : false,
		"bFilter": false,
		"bPaginate": false,
		"bRetrieve":false,
		"bProcessing" : false,
		"bDestroy" : true,
		
		"fnFooterCallback": testme,
		
		"aoColumns" : [
		{
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {
				return "<input type='checkbox'  id='selectlineitem_row"+ liCounter +"'>";
			},
			"bUseRendered" : false
		},  {
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"bUseRendered" : false,
			"fnRender" : function(obj) {
					return obj.aData[1];
			},
		}, {
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {return "<div style='padding:6px;'><input  type='text' size='45' class='textbox' id='itemdesc_row"+ liCounter +"'  ><div>";},
			"bUseRendered" : false
		},{
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {return "<div style='padding:6px;'><input type='text' size='25' class='textbox' id='partnumber_row"+ liCounter +"'><div>";},
			"bUseRendered" : false
		}, {
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) { return "<input type='text' size='10' class='textbox'  onblur='javascript:liupdatetotalprice("+liCounter+ ");' id='itemqty_row"+ liCounter +"'>";},
			"bUseRendered" : false
		}, {
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {return "<input type='text' size='12' class='textbox findIcon3' onclick='javascript:showUOMDialog(this,uom_cache.data,null);' id='unitofmeasure_row"+ liCounter +"'>";},
			"bUseRendered" : false
		},
		
		{
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {return "<input type='text' size='10'  class='textbox' onblur='javascript:liupdatetotalprice("+liCounter+ ");' id='unitprice_row"+ liCounter +"'>";},
			"bUseRendered" : false
		},
		
		{
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {return "<div style='width:50px;' id='totalprice_row"+ liCounter +"'></div>";},
			"bUseRendered" : false
		}
		
		
		
		]
	});
	
	jQuery('#ctx_buyer_line_item_tbl').prev().remove();
	jQuery('#ctx_buyer_line_item_tbl').next().remove();
	
	jQuery('#ctx_buyer_line_item_tbl tbody tr').live('click', function (event) {        
	    var aData = jQuery('#ctx_buyer_line_item_tbl').dataTable().fnGetData(this); // get datarow
	    var isRowSelected = jQuery(jQuery(this).find("td:first")).children()[0].checked; 
	    
	    if (isRowSelected)  // null if we clicked on title row
	    {
	    	jQuery(this).addClass('row_selected');
	    } else{
	    	jQuery(this).removeClass('row_selected');
	    }
	});

	addRow('ctx_buyer_line_item_tbl');
	jQuery('#ctx_buyer_line_item_tbl').dataTable().fnSetColumnVis( 3, false );
	
	

}




	





function getSelectedRows(tableId){
	var selectedTRs = jQuery('.row_selected'); //first parent is tbody and its parent is table id.
	var mySelectedTRs = new Array();
	for(var i=0;i<selectedTRs.length;i++){
		var jObj = jQuery(selectedTRs[i]);
		if(jObj.parent().parent().attr('id') == tableId){
			mySelectedTRs.push(selectedTRs[i]);
		}
	}
	return mySelectedTRs;
}

function deleteSelectedRows(tableId){
	var selectedTRs = getSelectedRows(tableId);
	for(var i=0;i<selectedTRs.length;i++){
		jQuery('#'+tableId).dataTable().fnDeleteRow(selectedTRs[i]);
		//.remove();
	}
	
	updateLineItemNumber();
	
	getlineitemtotals();
	//update for p
}

function updateLineItemNumber(){
	var allrecord  = jQuery('#ctx_buyer_line_item_tbl').dataTable().fnGetNodes( );
	for(var i=0;i<allrecord.length;i++){
		var sRecord = allrecord[i];
		jQuery('#ctx_buyer_line_item_tbl').dataTable().fnUpdate(i+1,sRecord, 1 ); //update line number cell
	}
}

function addRow(tableId){
	liCounter++;
	jQuery('#'+tableId).dataTable().fnAddData([false,liCounter,"","","","","","",""]);
	updateLineItemNumber();
}



var ATTACHMENT_COMP_FOR_NEW_PO = "poNum";





function this_selectSupplier(selectedRecord){
	render_supplierInfo(selectedRecord);
		
}

function render_supplierInfo(comp){
	if(comp != null){
		//Show Supplier name
		dwr.util.setValue('po_supplier',comp.companyName);
		dwr.util.setValue('po_suppid',comp.companyId);
		//Show supplier payment terms
		var options = new Array();
		dwr.util.removeAllOptions('supppmtterms');
		options.push({id:'', desc: '                   '});
		if(comp.paymentTerms != null && comp.paymentTerms.length>0){
			for(var i=0;i<comp.paymentTerms.length;i++){
				var term = getPaymentTerm(comp.paymentTerms[i]);
				options.push(term);
			}
		}
		dwr.util.addOptions('supppmtterms',options,'id','desc');
		
		//Populate supplier locations
		var options2 = new Array();
		dwr.util.removeAllOptions('supplocations');
		options2.push({id:'', desc: '                   '});
		if(comp.locations != null && comp.locations.length>0){
			for(var i=0;i<comp.locations.length;i++){
				var addrs = getFormattedAddress(comp.locations[i]);
				options2.push(addrs);
			}
		}
		dwr.util.addOptions('supplocations',options2,'id','desc');

	}else{
		showusrmessage("Please select Supplier.");
	}
}

function showAddressSelect(addrtype){
	render_jqAddressSelect(addrtype);
	dwr.util.setValue('toseladdresstype',addrtype);
	var dialog = jQuery('#ctx_poaddress_tbl_div').dialog({
		autoOpen: false,
		title: 'Select Address',
		 height: 400,
		 width:400
	});
	
	dialog.dialog('open');
	return false;
}

var ctx_buyer_po_addr_sel = null;
function render_jqAddressSelect(type){
	var data = new Array();
	if(usr_comp_cache != null && usr_comp_cache.locations != null){
		for(var i=0;i<usr_comp_cache.locations.length;i++){
			if(type == 'billing' && usr_comp_cache.locations[i].billingAddress == 'Y'){
				data.push(usr_comp_cache.locations[i]);
			}else if(type == 'shipping' && usr_comp_cache.locations[i].shippingAddress == 'Y'){
				data.push(usr_comp_cache.locations[i]);
			}
		}
	}
	ctx_buyer_po_addr_sel = jQuery('#ctx_poaddress_tbl_tbl').dataTable({
		"bProcessing" : true,
		"aaData" : data,
		"bJQueryUI" : true,
		"bSortClasses" : false,
		"bRetrieve" : true,
		
		
		"aoColumns" : [
		{
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {
				return "<input type='radio' id='addrId" + obj.aData.locationId+ "' name='addrSelectGrp'>";
			},
			"bUseRendered" : false
		},  {
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {
				var aData = obj.aData;
				return aData.addressLine1 + "<br>" + aData.addressLine2 + "<br>" + aData.city + " " + aData.state + " " + aData.zip;
			},
			"bUseRendered" : false
		}		
		]
	});
}

var ctx_posent_All_table = null;
function render_jqpos_all_table() {
	
	ctx_posent_All_table = jQuery('#ctx_bc_po_sent_All_tbl').dataTable({
		"bProcessing" : true,
		"aaData" : posent_cache,
		"bJQueryUI" : true,
		"bSortClasses" : false,
		 "bRetrieve":true,
		"aoColumns" : [ {
			"mDataProp" : "orderNumber",
			"sClass": "alignCenter",
			"fnRender" : function(obj) {
				var onum = obj.aData.orderNumber;

				return "<a href='javascript:void(0);'>" + onum + "</a>";
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : "orderDate",
			"sType" : "date",
			"sClass": "alignCenter",
			"fnRender" : function(obj) {

				return format_date(obj.aData.orderDate);
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : "clientNameText",
			"sClass": "alignCenter"
			
		}, {
			"mDataProp" : "orderAmount",
			"sClass": "alignCenter",
			"fnRender" : function(obj) {
				var om = (isEmptyString(obj.aData.unitCurrencySymbol)? "USD" : obj.aData.unitCurrencySymbol )+ " " +  format_currency(obj.aData.orderAmount);
				
				return om;
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : "invoicedAmount",
			"sClass": "alignCenter",
			"fnRender" : function(obj) {
				var om = (isEmptyString(obj.aData.unitCurrencySymbol)? "USD" : obj.aData.unitCurrencySymbol )+ " " +  format_currency(obj.aData.invoicedAmount);
				
				return om;
			},
			"bUseRendered" : false
		}, {
			"mDataProp" : "poStatus",
			"sClass": "alignCenter",
			"fnRender" : function(obj) {
				var om = obj.aData.poStatus;
				
				if(isEmptyString(om) || om == G_STATUS_MAP["PO_STATUS_NEW"]){
					om = "Sent"
				}else if(om == G_STATUS_MAP["PO_STATUS_NEW"]){
					om = "Fully Invoiced";
				}else if(om == G_STATUS_MAP["PO_STATUS_FULLY_INVOICED"]){
					om = "Fully Invoiced";
				}else if(om == G_STATUS_MAP["PO_STATUS_PARTIALLY_INVOICED"]){
					om = "Partially Invoiced";
				}else if(om == G_STATUS_MAP["PO_STATUS_CANCELLED"]){
					om = "Cancelled";
				}else if(om == G_STATUS_MAP["PO_STATUS_FAILED"]){
					om = "Failed";
				}else {
					om = "Status not Available."
				}
				
				return om;
			},
			"bUseRendered" : false
		},{
			"mDataProp" : "orderOwner","sClass": "alignCenter"
		},{
			"mDataProp" : "versionNumber","sClass": "alignCenter"
		} ]
	});
	
	
	//ctx_posent_table.children('td').attr('align', 'center');

}


//---- Purchase Order Create Code --- //

function po_initpocreatescreen(){
	dwr.util.setValue('totalpoamt',0);
	dwr.util.setValue('po_createdate', format_date(new Date()));
	dwr.util.setValue('po_reqby', usrname);
	//dwr.util.setValue('po_preparedby', usrname);
	dwr.util.setValue('poNum', '');
	jQuery("#poNum").removeAttr("disabled");

	dwr.util.setValue('poName', '');
	dwr.util.setValue('potype', 'S');
	dwr.util.setValue('po_supplier', '');
	dwr.util.setValue('po_suppid', '');
	dwr.util.setValue('supppmtterms', '');
	dwr.util.setValue('supplocations', '');
	dwr.util.setValue('b_selloc', '');
	dwr.util.setValue('b_addr_line1', '');
	dwr.util.setValue('b_addr_line2', '');
	dwr.util.setValue('b_address_3', '');
	dwr.util.setValue('b_city', '');
	dwr.util.setValue('b_state', '');
	dwr.util.setValue('b_zip', '');
	dwr.util.setValue('s_selloc', '');
	dwr.util.setValue('s_addr_line1', '');
	dwr.util.setValue('s_addr_line2', '');
	dwr.util.setValue('s_address_3', '');
	dwr.util.setValue('s_city', '');
	dwr.util.setValue('s_state', '');
	dwr.util.setValue('s_zip', '');
	dwr.util.setValue('toseladdresstype', '');
	
	assignAttachmentComponent("attachmentComponetPlaceHolder_NewPO",ATTACHMENT_COMP_FOR_NEW_PO);
	assignCommentsComponent("commentComponetPlaceHolder1");
	liCounter = 0;
	po_generatePONum();
	try{
	render_jqLineItemTable();
	}catch(ex){}
}

	
	

function po_generatePONum(){
	var dwrCallMetaData = {
		callback : success_autogentponum,
		exceptionHandler : null,
		timeout : 100000,
		errorHandler : null
	};

	DWR_PurchaseOrders.getAutogeneratedOrderNumber("PURCHASE_ORDER",
			dwrCallMetaData);
}

var g_po_num = null;

function success_autogentponum(dwrresp) {
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null
				&& !isEmptyString(dwrresp.objRespOrError)) {
			g_po_num = dwrresp.objRespOrError;
			dwr.util.setValue('poNum', dwrresp.objRespOrError);
			jQuery("#poNum").attr("disabled", "disabled");
		}
	}
}

function this_selectAddress(){
	var rdos = jQuery("input[name='addrSelectGrp']");
	var l = rdos.length;
	for(var s=0;s<l;s++){
		if(rdos[s].checked){
			var locId = rdos[s].id.replace('addrId','');
			render_locInAddres(locId);
			break;
		}
	}
}

function render_locInAddres(locId){
	var atype = dwr.util.getValue('toseladdresstype');
	var sloc = null;
	if(usr_comp_cache != null && usr_comp_cache.locations != null){
		for(var i=0;i<usr_comp_cache.locations.length;i++){
			if(usr_comp_cache.locations[i].locationId == locId){
				sloc = usr_comp_cache.locations[i];
				break;
			}
		}
	}
	if(sloc != null){
		if(atype == 'billing'){
			dwr.util.setValue('b_selloc',locId);
			dwr.util.setValue('b_addr_line1',sloc.addressLine1);
			dwr.util.setValue('b_addr_line2',sloc.addressLine2);
			dwr.util.setValue('b_address_3',sloc.addressLine3);
			dwr.util.setValue('b_city',sloc.city);
			dwr.util.setValue('b_state',sloc.state);
			dwr.util.setValue('b_zip',sloc.zip);
			
		}else if(atype == 'shipping'){
			dwr.util.setValue('s_selloc',locId);
			dwr.util.setValue('s_addr_line1',sloc.addressLine1);
			dwr.util.setValue('s_addr_line2',sloc.addressLine2);
			dwr.util.setValue('s_address_3',sloc.addressLine3);
			dwr.util.setValue('s_city',sloc.city);
			dwr.util.setValue('s_state',sloc.state);
			dwr.util.setValue('s_zip',sloc.zip);
		}
	}
	jQuery('#ctx_poaddress_tbl_div').dialog('close');
}
function this_resetSelectAddress(){
	jQuery("input[name='addrSelectGrp']").attr('checked',false);
}




function getFormattedAddress(addr){
	return { id: addr.locationId, desc: addr.addressLine1 + " " + addr.addressLine2 + " " + addr.city + " " + addr.state + " " + addr.zip };
}

function liupdatetotalprice(licounter){
	var q = dwr.util.getValue('itemqty_row'+licounter);
	var u = dwr.util.getValue('unitprice_row'+licounter);
	var p = 0;
	if(!isEmptyString(q) && !isEmptyString(u) && !isNaN(Number(q)) && !isNaN(Number(u))){
		p = Number(q)*Number(u);
	}
	
	dwr.util.setValue('totalprice_row'+licounter,p);
	getlineitemtotals();
}

function savepo(){
	//validate
	var errMsg = new Array();
	//check PO number.
	var ponum = dwr.util.getValue('poNum');
	if(isEmptyString(ponum)){
		errMsg.push("Purchase Order# is required.");
	}
	
	//Check Supplier, Supplier Payment Terms, Supplier location.
	var supid = dwr.util.getValue('po_suppid');
	if(isEmptyString(supid)){
		errMsg.push("Supplier is required.");
	}

	var supmtt = dwr.util.getValue('supppmtterms');
	var suploc = dwr.util.getValue('supplocations');
	
	if(isEmptyString(supmtt)){
		errMsg.push("Supplier Payment Term is required.");
	}
	
	if(isEmptyString(suploc)){
		errMsg.push("Supplier Location is required.");
	}
	
	//Billing , Shipping Address.
	var b_loc = dwr.util.getValue('b_selloc');
	var s_loc = dwr.util.getValue('s_selloc');

	
	if(isEmptyString(b_loc) || isEmptyString(s_loc)){
		errMsg.push("Billing/ Shipping address is required.");
	}
	
	if(isEmptyString(dwr.util.getValue('poName'))){
		errMsg.push("Purchase Order Name is required");
	}
	
	var amt = dwr.util.getValue('totalpoamt');
	if(isEmptyString(amt) || isNaN(Number(amt))) {
		errMsg.push("Line Item amounts/ Total amount is not valid.");
	}
	
	if(amt == 0) {
		errMsg.push("Line Item must be greater than zero");
	}
	
	if(!validateLI()){
		errMsg.push("Please Put Description For Line Item(s)");
	}
	
	if(errMsg.length > 0){
		var txt = "<span class='lable w100' style='font-size:8pt;'>Please Enter the following fields:</span><br><span class='redtxt w100' style='font-size:8pt;'>-" + errMsg.join("<br>-") + "</span>";
		showusrmessage(txt);
		return;
	}
	
	var b_s = null;
	var s_s = null;
	var sp_s = null;
	
	 for(var k=0;k<comp_preferred_cache.length;k++){
		 if(comp_preferred_cache[k].companyId == b_loc){
			 b_s = comp_preferred_cache[k];
		 }
		 
		 if(comp_preferred_cache[k].companyId == s_loc){
			 s_s = comp_preferred_cache[k];
		 }
		 
		 if(comp_preferred_cache[k].companyId == suploc){
			 sp_s = comp_preferred_cache[k];
		 }
	 }
	
	//build po object and make dwr call.
	var po_obj = {
		orderNumber : ponum,
		orderTitle : dwr.util.getValue('poName'),
		orderSupplier : supid,
		supplierLocation : sp_s,
		orderStatus: "Sent",
		orderDate : new Date(),
		orderCompany : usrcompany_uid,
		orderOwner : dwr.util.getValue('po_reqby'),
		//orderComposer : dwr.util.getValue('po_preparedby'),
		originatingCompany : usrcompany_uid,
		orderAmount : Number(amt),
		lastModifiedDate : new Date(),
		prevVersionNumber : null,
		nextVersionNumber : null,
		versionNumber : "1",
		changeOrderInitiatedBy : loggedinuser,
		orderPaymentTermId : supmtt,
		orderLineItems : getlineitems(),
		orderBillToAddress : b_s,
		orderShipToAddress : s_s,
		type:dwr.util.getValue('potype')
	};
	
	try{
		var poAtchArr = new Array();
		if(attachmentctr > 0){
			for(var ip=0;ip<attachmentctr;ip++){
				if(document.getElementById('poattachments_check'+ip+'').checked){
					
					poAtchArr.push(dwr.util.getValue('poaattach_id'+ip+''));
				}
			}
		}
		
		if(poAtchArr.length > 0){
			po_obj.orderAttachmentsId = poAtchArr;
		}
		
		
		var pocmtarr = new Array();
		if(pocomments_ctr > 0){
			for(var iq=0;iq<pocomments_ctr;iq++){
				if(document.getElementById('pocomment_check'+iq+'').checked){
					pocmtarr.push(dwr.util.getValue('pocomment_text'+iq+''));
				}
			}
		}
		
		if(pocmtarr.length > 0){
			po_obj.orderComments = pocmtarr;
		}
	}catch(ex){
		
	}
	
		var dwrCallMetaData = {
			callback : success_savepo,
			exceptionHandler : ysn_dwrerror_handler,
			timeout : 100000,
			errorHandler : ysn_dwrerror_handler
		};
		DWR_PurchaseOrders.createOrSavePurchaseOrder(po_obj, true, dwrCallMetaData);
}

function success_savepo(dwrresp){
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null
				&& !isEmptyString(dwrresp.objRespOrError)) {
			showusrmessage("Purchase Order: " + dwrresp.objRespOrError + " created successfully");
			po_initpocreatescreen();
			return;
		}
	}

	showusrmessage("Purchase Order could not be created. Please try again.");
}

function setuppotype(){
	if(dwr.util.getValue('potype') == "G"){
		jQuery('#ctx_buyer_line_item_tbl').dataTable().fnSetColumnVis( 3, true );
	}else{
		jQuery('#ctx_buyer_line_item_tbl').dataTable().fnSetColumnVis( 3, false );
	}
}


function getlineitems(){
	var ponum = dwr.util.getValue('poNum');
	var orderLineItems = new Array();
	var t = dwr.util.getValue('potype');
	for(var i=1;i<=liCounter;i++){
		if(jQuery('#itemdesc_row'+i).length == 1){
			var litem = {};
			litem.orderNumber = ponum;
			litem.orderLineItemNumber = ponum + "_LI" + i;
			if(t == 'G'){
				litem.partNumber = dwr.util.getValue('itemqty_row'+i);
			}
			litem.quantity = dwr.util.getValue('partnumber_row'+i);
			litem.lineDescription = dwr.util.getValue('itemdesc_row'+i);
			litem.uomSymbol = dwr.util.getValue('unitofmeasure_row'+i);
			litem.unitPrice = dwr.util.getValue('unitprice_row'+i);
			litem.unitCurrencySymbol =  dwr.util.getValue('USD');
			litem.lineAmount = dwr.util.getValue('totalprice_row'+i);
			orderLineItems.push(litem);
		}		
	}
	
	return orderLineItems;
}

function getlineitemtotals(){
	var total = 0;
	for(var i=1;i<=liCounter;i++){
		if(jQuery('#itemdesc_row'+i).length == 1){
			var t = dwr.util.getValue('totalprice_row'+i);
			if(!isEmptyString(t) && !isNaN(Number(t))){
				total = total + Number(t);
			}
		}		
	}
	
	dwr.util.setValue('totalpoamt',total);
}

function validateLI(){
	var isValid = true;
	for(var i=1;i<=liCounter;i++){
		if(jQuery('#itemdesc_row'+i).length == 1){
			var desc = dwr.util.getValue('itemdesc_row'+i);
			if(isEmptyString(desc)){
				isValid =  false;
			} 
			
		}		
	}
	return isValid;
}


//render PO starts here////////////
ctx_buyer_update_LItable = null;

function showPODetails(){
	hideAllScreen();
	jQuery('#poDetailContainer').addClass('show').removeClass('hide');
	jQuery( "#poDetailContainer" ).tabs().show(0);
	
	render_jq_updateLineItemTable();
	assignAttachmentComponent("attachmentComponetPlaceHolder_OpenPO",ATTACHMENT_COMP_FOR_OPEN_PO);
	assignCommentsComponent("commentsComponetPlaceHolder_OpenPO");
	
	
	
}
function render_jq_updateLineItemTable() {
	ctx_buyer_update_LItable = jQuery('#ctx_buyer_update_line_item_tbl').dataTable({
		"aaData" : {},
		"bJQueryUI" : true,
		"bSortClasses" : false,
		"bFilter": false,
		"bPaginate": false,
		"bRetrieve":false,
		"bProcessing" : false,
		"bDestroy" : true,
		
		"fnFooterCallback": liUpdateCallBack,
		
		"aoColumns" : [
		{
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {
				
				if(isEmptyString(obj.aData[0])){
					return "<input type='checkbox'  id='update_selectlineitem_row"+ selPO_liCounter +"'>";
				}else{
					return "<input type='checkbox' disabled id='update_selectlineitem_row"+ selPO_liCounter +"'>";
				}
				
			},
			"bUseRendered" : false
		},  {
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"bUseRendered" : false,
			"fnRender" : function(obj) {
					return obj.aData[1];
			}
		}, {
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {return "<div style='padding:6px;'><input value='"+ obj.aData[2] +"' type='text' size='25' class='textbox' id='update_itemdesc_row"+ selPO_liCounter +"'  ><div>";},
			"bUseRendered" : false
		},{
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {return "<div style='padding:6px;'><input value='"+ obj.aData[3] +"' type='text' size='25' class='textbox' id='update_partnumber_row"+ selPO_liCounter +"'><div>";},
			"bUseRendered" : false
		}, {
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) { return "<input type='text' size='10' value='"+ obj.aData[4] +"' class='textbox' onblur='javascript:liupdatetotalprice("+selPO_liCounter+ ");' id='update_itemqty_row"+ selPO_liCounter +"'>";},
			"bUseRendered" : false
		}, {
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {
				
				return  "<input type='text' size='10'  class='textbox' value='"+ obj.aData[5] +"' id='update_unitofmeasure_row"+ selPO_liCounter +"'>";},
			"bUseRendered" : false
		},
		
		{
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {return "<input type='text' size='10' value='"+ obj.aData[6] +"'  class='textbox' onblur='javascript:update_liupdatetotalprice("+selPO_liCounter+ ");' id='unitprice_row"+ selPO_liCounter +"'>";},
			"bUseRendered" : false
		},
		
		{
			"mDataProp" : null,
			"sClass": "alignCenter",
			"bSortable": false,
			"fnRender" : function(obj) {return "<div style='width:50px;' value='"+ obj.aData[7] +"' id='update_totalprice_row"+ selPO_liCounter +"'></div>";},
			"bUseRendered" : false
		}
		
		
		
		]
	});
	
	jQuery('#ctx_buyer_update_line_item_tbl').prev().remove();
	jQuery('#ctx_buyer_update_line_item_tbl').next().remove();
	
	jQuery('#ctx_buyer_update_line_item_tbl tbody tr').live('click', function (event) {        
	    var aData = jQuery('#ctx_buyer_update_line_item_tbl').dataTable().fnGetData(this); // get datarow
	    var isRowSelected = jQuery(jQuery(this).find("td:first")).children()[0].checked; 
	    
	    if (isRowSelected)  // null if we clicked on title row
	    {
	    	jQuery(this).addClass('row_selected');
	    } else{
	    	jQuery(this).removeClass('row_selected');
	    }
	});

}


var selPO_liCounter = 0;

function liUpdateCallBack(nFoot,aaData, iStart, iEnd,aiDisplay ){
	for ( var i=0 ; i<aaData.length ; i++ )
	{
		aaData[i][1] = i+1 ;
	}
    
}

function addLIForSelectedPO(tableId,obj){
	selPO_liCounter++;
	if(obj != null){
		console.log(obj);
		jQuery('#'+tableId).dataTable().fnAddData([obj.lineItemUniqueId,selPO_liCounter,obj.lineDescription,obj.partNumber,
		                                           obj.quantity,obj.uomSymbol,obj.unitPrice,obj.lineAmount]);
		updateLineItemNumberForSelPO();
	} else{
		console.log(obj);
		jQuery('#'+tableId).dataTable().fnAddData(["",selPO_liCounter,"","","","","",""]);
		updateLineItemNumberForSelPO();
	}
	
	
}

function updateLineItemNumberForSelPO(){
	var allrecord  = ctx_buyer_update_LItable.dataTable().fnGetNodes();
	for(var j=0;i<allrecord.length;j++){
		var sRecord = allrecord[j];
		console.log(j+1);
		ctx_buyer_update_LItable.fnUpdate(j+1,sRecord,1); //update line number cell
	}
}



function populatedLIforSelectedPO(posent_cache_Obj){
	
		for(var i=0;i<posent_cache_Obj.orderLineItems.length;i++){
			addLIForSelectedPO("ctx_buyer_update_line_item_tbl",posent_cache[i].orderLineItems[i]);
		}
	
	
	
}

function deleteSelectedRowsForSelectedPO(tableId){
	var selectedTRs = getSelectedRows(tableId);
	for(var i=0;i<selectedTRs.length;i++){
		jQuery('#'+tableId).dataTable().fnDeleteRow(selectedTRs[i]);
		//.remove();
	}
	
	updateLineItemNumberForSelPO();
	
	//getlineitemtotals();
	//update for p
}



function populateSelectedPO(selectedPO){
	
	
	dwr.util.setValue("poStatusShow",getStatus(selectedPO.poStatus));
	dwr.util.setValue("poNameShow",selectedPO.orderTitle);
	
	//dwr.util.setValue("poTypeShow",selectedPO.);
	
	dwr.util.setValue("poCreateDateShow",selectedPO.orderDate);
	dwr.util.setValue("poOwnerShow",selectedPO.orderOwner);
	dwr.util.setValue("poSupplierShow",selectedPO.clientNameText);
	dwr.util.setValue("poPYShow",selectedPO.orderPaymentTermId);
	dwr.util.setValue("poLocationShow",selectedPO.supplierLocation);
	dwr.util.setValue("poTypeShow",selectedPO.type);
	try{
		assignReadOnlyAttachmentComponent("po_existingAttachmentLink",selectedPO.orderAttachmentsId);
		
		displayPrevComments("po_existingComments",selectedPO.orderComments);
	}catch(ex){
		
	}
	
	populatedLIforSelectedPO(selectedPO);
	
	
	
	
}

function resetOpenPO(){

	dwr.util.setValue("poStatusShow","");
	dwr.util.setValue("poNameShow","");
	dwr.util.setValue("poCreateDateShow","");
	dwr.util.setValue("poOwnerShow","");
	dwr.util.setValue("poSupplierShow","");
	dwr.util.setValue("poPYShow","");
	dwr.util.setValue("poLocationShow","");
	dwr.util.setValue("poTypeShow","");
	dwr.util.setValue("poNumShow","");
	jQuery("#poNumShow").removeAttr("disabled");
	jQuery("#po_existingAttachmentLink").html("");
	jQuery("#po_existingComments").html("");

	
	
	
}